package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping(value = "/file")
@CrossOrigin
public class FileUploadController {
    /**上传地址*/
    @Value("${file.upload.path}")
    private String filePath;

    @GetMapping("/fileupload")
    public ModelAndView getFile(){
        return new ModelAndView("fileupload");
    }

    @GetMapping("/imageview")
    public String imageview(){
        return "imageview";
    }

    @GetMapping
    public String imageview(Model model){
        String url="localhost:8080/images/leisheng.jpg";
        model.addAttribute("key",url);
        return "imageview";
    }

    @PostMapping(value = "/upload")
    public ResponseEntity<?> upload(@RequestParam("myfile") MultipartFile multipartFile){
        System.out.println("文件上传"+multipartFile.getOriginalFilename());
        String filename = multipartFile.getOriginalFilename();
        String path = filePath;
        File filepath=new File(path);
        if(!filepath.exists()){
            filepath.mkdir();
        }
        try {
            multipartFile.transferTo(new File(path + File.separator + filename));
            /*String url="http:/localhost:8080";
            url+=*/
        } catch (IOException e) {
            e.printStackTrace();
        }

        // String url=this.getClass().getClassLoader().getResource("static").getFile();
        // System.out.println(url);
        return ResponseEntity.ok().body(true);


    }
}

